<template>
  <div>
    <el-row>
      <el-button type="primary" @click="addRole">添加角色</el-button>
    </el-row>
    <el-table style="margin-top: 15px" border stripe :data="rolesList">
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            style="padding: 15px"
            :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
            v-for="(item1, index1) in scope.row.children"
            :key="item1.id"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag
                closable
                @close="closeTag(scope.row, item1.id)"
                effect="dark"
                >{{ item1.authName }}</el-tag
              >
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级、三级权限 -->
            <el-col :span="19">
              <el-row
                :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                v-for="(item2, index2) in item1.children"
                :key="item2.id"
              >
                <!-- 渲染二级权限 -->
                <el-col :span="6">
                  <el-tag
                    @close="closeTag(scope.row, item2.id)"
                    closable
                    effect="dark"
                    type="success"
                    >{{ item2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染三级权限 -->
                <el-col :span="18">
                  <el-tag
                    closable
                    effect="dark"
                    type="warning"
                    @close="closeTag(scope.row, item3.id)"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="80px"> </el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="editRole(scope.row)"
            icon="el-icon-edit"
            >编辑角色</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="delRole(scope.row)"
            icon="el-icon-delete"
            >删除</el-button
          >
          <el-button
            size="mini"
            @click="showTree(scope.row)"
            type="warning"
            icon="el-icon-setting"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增编辑弹窗 -->
    <el-dialog
      :title="isEdit === true ? '编辑角色' : '添加角色'"
      :visible.sync="addRoleShow"
    >
      <el-form v-if="addRoleShow" ref="form" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleShow = false">取 消</el-button>
        <el-button type="primary" @click="onAddRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色树展示 -->
    <el-dialog
      title="分配权限"
      :visible.sync="distributionShow"
      @close="closeTree"
    >
      <div v-if="distributionShow">
        <el-tree
          node-key="id"
          default-expand-all
          :default-checked-keys="defaultArr"
          :data="TreeData"
          show-checkbox
          :props="defaultProps"
          ref="tree"
        ></el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="distributionShow = false">取 消</el-button>
        <el-button type="primary" @click="setTree">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleListApi,
  delRoleApi,
  addRoleApi,
  editRoleApi,
  delRolesApi,
  getRightApi,
  setRightApi,
} from '../../../api/roles';
// ,
export default {
  data() {
    return {
      setId: null,
      defaultArr: [],
      TreeData: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      distributionShow: false,
      rolesList: [],
      addRoleShow: false,
      form: {
        roleName: '',
        roleDesc: '',
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      isEdit: false,
      editId: null,
    };
  },
  methods: {
    closeTree() {
      this.defaultArr = [];
    },
    async setTree() {
      const keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(',');
      const res = await setRightApi({ rids: idStr }, this.setId);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRoles();
      this.distributionShow = false;
    },
    showTree(row) {
      this.distributionShow = true;
      this.defaultArr = row.children;
      this.setId = row.id;
      this.getTreeData();
      this.getLeafKeys(row, this.defaultArr);
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前节点不包含children属性，则是三级权限节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    async getTreeData() {
      const res = await getRightApi();
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.TreeData = res.data;
    },
    // 删除角色
    delRole(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await delRolesApi(row.id);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          this.getRoles();
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 打开编辑弹窗数据回填
    editRole(row) {
      this.isEdit = true;
      this.addRoleShow = true;
      this.editId = row.id;
      this.form.roleName = row.roleName;
      this.form.roleDesc = row.roleDesc;
    },
    // 提交事件
    onAddRole() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        this.isEdit ? this.doEdit() : this.doAdd();
      });
    },
    // 编辑
    async doEdit() {
      const res = await editRoleApi(this.form, this.editId);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRoles();
      this.addRoleShow = false;
    },
    // 做添加
    async doAdd() {
      const res = await addRoleApi(this.form);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getRoles();
      this.addRoleShow = false;
    },
    // 添加角色
    addRole() {
      this.isEdit = false;
      this.addRoleShow = true;
      this.form = {
        roleName: '',
        roleDesc: '',
      };
    },
    // 获取角色列表
    async getRoles() {
      const res = await getRoleListApi();
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
    },
    // 删除权限
    closeTag(row, rid) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await delRoleApi(row.id, rid);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          row.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
  },
  created() {
    this.getRoles();
    // this.getTreeData();
  },
};
</script>

<style lang='less' >
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
